<template>
  <div class="p-2">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter"
                :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div v-show="showSearch" class="mb-[10px]">
        <el-card shadow="hover">
          <el-form ref="queryFormRef" :model="queryParams" :inline="true">
            <el-form-item label="客户名称" prop="name">
              <el-input v-model="queryParams.name" placeholder="请输入客户名称" clearable @keyup.enter="handleQuery"/>
            </el-form-item>
            <el-form-item label="code" prop="code">
              <el-input v-model="queryParams.code" placeholder="请输入客户code" clearable @keyup.enter="handleQuery"/>
            </el-form-item>
            <el-form-item label="状态" prop="status">
              <el-select v-model="queryParams.status" placeholder="请选择状态" clearable>
                <el-option v-for="dict in cstm_customer_status" :key="dict.value" :label="dict.label"
                           :value="dict.value"/>
              </el-select>
            </el-form-item>
            <el-form-item label="接入方式" prop="method">
              <el-input v-model="queryParams.method" placeholder="请输入接入方式" clearable @keyup.enter="handleQuery"/>
            </el-form-item>
            <el-form-item label="公司账号" prop="corporateId">
              <!--              <el-input v-model="queryParams.corporateId" placeholder="请输入公司账号id" clearable @keyup.enter="handleQuery" />-->
              <el-select v-model="queryParams.corporateId" placeholder="请选择公司账号" clearable>
                <el-option v-for="dict in allCorporateList" :key="dict.id" :label="dict.name" :value="dict.id"/>
              </el-select>
            </el-form-item>
            <el-form-item label="单价" prop="price">
              <el-input v-model="queryParams.price" placeholder="请输入单价" clearable @keyup.enter="handleQuery"/>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
              <el-button icon="Refresh" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </div>
    </transition>

    <el-card shadow="never">
      <template #header>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" plain icon="Plus" @click="handleAdd" v-hasPermi="['customer:customer:add']">新增
            </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate()"
                       v-hasPermi="['customer:customer:edit']">修改
            </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete()"
                       v-hasPermi="['customer:customer:remove']">删除
            </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="warning" plain icon="Download" @click="handleExport"
                       v-hasPermi="['customer:customer:export']">导出
            </el-button>
          </el-col>
          <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>
      </template>

      <el-table v-loading="loading" :data="customerList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center"/>
        <el-table-column label="客户ID" align="center" prop="id" v-if="true"/>
        <el-table-column label="客户名称" align="center" prop="name"/>
        <el-table-column label="客户code" align="center" prop="code"/>
        <el-table-column label="客户密码" align="center" prop="pwd"/>
        <el-table-column label="ip白名单" align="center" prop="ips"/>
        <el-table-column label="状态" align="center" prop="status">
          <template #default="scope">
            <dict-tag :options="cstm_customer_status" :value="scope.row.status"/>
          </template>
        </el-table-column>
        <el-table-column label="接入方式" align="center" prop="method"/>
        <el-table-column label="公司账号id" align="center" prop="corporateId"/>
        <el-table-column label="单价" align="center" prop="price"/>
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)"
                       v-hasPermi="['customer:customer:edit']">修改
            </el-button>
            <el-button link type="primary" icon="Edit" @click="openChannelDialog(scope.row.id)"
                       v-hasPermi="['customer:customer:bindProviderChannel']">供应商通道
            </el-button>
            <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)"
                       v-hasPermi="['customer:customer:remove']">删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum"
                  v-model:limit="queryParams.pageSize" @pagination="getList"/>
    </el-card>
    <!-- 添加或修改下游客户对话框 -->
    <el-dialog :title="dialog.title" v-model="dialog.visible" width="500px" append-to-body>
      <el-form ref="customerFormRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="客户名称" prop="name">
          <el-input v-model="form.name" type="textarea" placeholder="请输入内容"/>
        </el-form-item>
        <el-form-item label="客户code" prop="code">
          <el-input v-model="form.code" placeholder="请输入客户code" readonly/>
        </el-form-item>
        <el-form-item label="客户密码" prop="pwd">
          <el-input v-model="form.pwd" placeholder="请输入客户密码" readonly/>
        </el-form-item>
        <el-form-item label="ip白名单" prop="ips">
          <el-input v-model="form.ips" placeholder="请输入ip白名单" type="textarea"/>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio
              v-for="dict in cstm_customer_status"
              :key="dict.value"
              :value="parseInt(dict.value)"
            >{{ dict.label }}
            </el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="公司账号" prop="corporateId">
          <el-select v-model="form.corporateId" placeholder="请选择公司账号" clearable :disabled="!!form.id">
            <el-option v-for="dict in allCorporateList" :key="dict.id" :label="dict.name" :value="dict.id"/>
          </el-select>
        </el-form-item>
        <el-form-item label="单价" prop="price">
          <el-input v-model="form.price" placeholder="请输入单价"/>
        </el-form-item>
        <el-form-item label="接入方式" prop="method">
          <el-select v-model="form.method" placeholder="请选择接入方式" clearable :disabled="!!form.id">
            <el-option v-for="dict in methodList" :key="dict" :label="dict" :value="dict"/>
          </el-select>
        </el-form-item>
        <!-- 接入方式参数配置 -->
        <template v-if="form.method === 'cmpp'">
          <el-form-item label="接入码" prop="methodParams.cmpp.spCode">
            <el-input v-model="methodParams.cmpp.spCode" placeholder="请输入接入码"/>
          </el-form-item>
          <el-form-item label="连接数" prop="methodParams.cmpp.connections">
            <el-input v-model="methodParams.cmpp.connections" type="number" min="1" max="20"
                      placeholder="请输入连接数"/>
          </el-form-item>
          <el-form-item label="受理速率" prop="methodParams.cmpp.acceptRate">
            <el-input v-model="methodParams.cmpp.acceptRate" type="number" min="1" max="3000"
                      placeholder="请输入受理速率"/>
          </el-form-item>
          <el-form-item label="回执带入上游码号" prop="methodParams.cmpp.needProviderDest">
            <el-select v-model="methodParams.cmpp.needProviderDest">
              <el-option v-for="dict in needProviderDestList" :key="dict.value" :label="dict.label"
                         :value="dict.value"/>
            </el-select>
          </el-form-item>
        </template>

        <template v-else-if="form.method === 'http'">
          <el-form-item label="受理速率" prop="methodParams.http.acceptRate">
            <el-input v-model="methodParams.http.acceptRate" type="number" min="1" max="3000"
                      placeholder="请输入受理速率"/>
          </el-form-item>
        </template>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
    <el-dialog title="供应商通道配置" v-model="channelDialog.visible" width="50%">
      <el-table :data="channelList" border>
        <el-table-column label="供应商通道" width="400">
          <template #default="{row}">
            <el-select v-model="row.providerChannelId" placeholder="选择通道" clearable>
              <el-option
                v-for="channel in allProviderChannels"
                :key="channel.id"
                :label="`${channel.channelName}`"
                :value="channel.id"
              />
            </el-select>
          </template>
        </el-table-column>
        <el-table-column label="权重" width="200">
          <template #default="{row}">
            <el-input-number v-model="row.weight" :min="0" :max="100" controls-position="right"/>
          </template>
        </el-table-column>
        <el-table-column label="状态" >
          <template #default="{row}">
            <el-switch
              v-model="row.status"
              :active-value="1"
              :inactive-value="0"
              active-text="启用"
              inactive-text="停用"
            />
          </template>
        </el-table-column>
        <el-table-column label="操作" >
          <template #default="{row, $index}">
            <el-button type="danger" icon="Delete" @click="removeChannel($index)"/>
          </template>
        </el-table-column>
      </el-table>
      <div style="margin-top: 10px">
        <el-button type="primary" icon="Plus" @click="addChannel">添加通道</el-button>
        <el-button type="success" @click="saveChannels">保存配置</el-button>
      </div>
    </el-dialog>
  </div>

  <!-- 供应商通道对话框 -->

</template>

<script setup name="Customer" lang="ts">
import {
  listCustomer,
  getCustomer,
  delCustomer,
  addCustomer,
  updateCustomer,
  newCustomer, bindProviderChannel,getCustomerChannels
} from '@/api/customer/customer';

import {CustomerVO, CustomerQuery, CustomerForm} from '@/api/customer/customer/types';
import {listCorporateAll} from "@/api/customer/corporate";
import {CorporateVO} from "@/api/customer/corporate/types";
import {listAllProviderChannel} from "@/api/provider/providerChannel";
import {ProviderChannelVO} from "@/api/provider/providerChannel/types";
import {CustomerProviderChannelVO} from "@/api/customer/customerProviderChannel/types";

const {proxy} = getCurrentInstance() as ComponentInternalInstance;
const {cstm_customer_status} = toRefs<any>(proxy?.useDict('cstm_customer_status'));

const customerList = ref<CustomerVO[]>([]);
const buttonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref<Array<string | number>>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const methodList = ref<Array<string>>(['cmpp', 'http']);

const queryFormRef = ref<ElFormInstance>();
const customerFormRef = ref<ElFormInstance>();

const dialog = reactive<DialogOption>({
  visible: false,
  title: ''
});

const initFormData: CustomerForm = {
  id: undefined,
  name: undefined,
  code: undefined,
  pwd: undefined,
  ips: undefined,
  status: undefined,
  method: undefined,
  corporateId: undefined,
  price: undefined,
}
const data = reactive<PageData<CustomerForm, CustomerQuery>>({
  form: {...initFormData},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    name: undefined,
    code: undefined,
    status: undefined,
    method: undefined,
    corporateId: undefined,
    price: undefined,
    params: {}
  },
  rules: {
    id: [
      {required: true, message: "客户ID不能为空", trigger: "blur"}
    ],
    method: [
      {required: true, message: "接入方式不能为空", trigger: "blur"}
    ],
    corporateId: [
      {required: true, message: "公司账号id不能为空", trigger: "blur"}
    ],
    price: [
      {required: true, message: "单价不能为空", trigger: "blur"}
    ],
    ips: [
      {required: true, message: "ip白名单不能为空", trigger: "blur"}
    ]
  }
});

const {queryParams, form, rules} = toRefs(data);

/** 查询下游客户列表 */
const getList = async () => {
  loading.value = true;
  const res = await listCustomer(queryParams.value);
  customerList.value = res.rows;
  total.value = res.total;
  loading.value = false;
}

/** 取消按钮 */
const cancel = () => {
  reset();
  dialog.visible = false;
}

/** 表单重置 */
const reset = () => {
  form.value = {...initFormData};
  customerFormRef.value?.resetFields();
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  handleQuery();
}

/** 多选框选中数据 */
const handleSelectionChange = (selection: CustomerVO[]) => {
  ids.value = selection.map(item => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
const handleAdd = async () => {
  reset();
  dialog.visible = true;
  dialog.title = "添加下游客户";
  const {data} = await newCustomer()
  console.log("handleAdd---", data);
  Object.assign(form.value, data);
}

/** 修改按钮操作 */
const handleUpdate = async (row?: CustomerVO) => {
  reset();
  const _id = row?.id || ids.value[0]
  const res = await getCustomer(_id);
  Object.assign(form.value, res.data);
  console.log("getCustomer",res.data);
  console.log("getCustomer",res.data.methodParams,JSON.parse(res.data.methodParams));
  Object.assign(methodParams, JSON.parse(res.data.methodParams));
  dialog.visible = true;
  dialog.title = "修改下游客户";
}

/** 提交按钮 */
const submitForm = () => {
  customerFormRef.value?.validate(async (valid: boolean) => {
    if (!valid) return;
    buttonLoading.value = true;

    // 整合参数到form.params中
    if (form.value.method === 'cmpp') {
      //判断接入码是否为空
      if (!methodParams.cmpp.spCode) {
        proxy?.$modal.msgError("接入码不能为空");
        buttonLoading.value = false;
        return;
      }
      //判断连接数是否为空
      if (!methodParams.cmpp.connections) {
        proxy?.$modal.msgError("连接数不能为空");
        buttonLoading.value = false;
        return;
      }
      //判断受理速率是否为空
      if (!methodParams.cmpp.acceptRate) {
        proxy?.$modal.msgError("受理速率不能为空");
        buttonLoading.value = false;
        return;
      }
      //回执带上游码号
      if (!methodParams.cmpp.needProviderDest) {
        proxy?.$modal.msgError("回执带入上游码号不能为空");
        buttonLoading.value = false;
        return;
      }


      form.value.methodParams = JSON.stringify({...methodParams.cmpp});
    } else if (form.value.method === 'http') {
      //判断受理速率是否为空
      if (!methodParams.http.acceptRate) {
        proxy?.$modal.msgError("受理速率不能为空");
        buttonLoading.value = false;
        return;
      }
      form.value.methodParams = JSON.stringify({...methodParams.http});
    }
    console.log("submitForm", form.value);
    if (form.value.id) {
      await updateCustomer(form.value).finally(() => buttonLoading.value = false);
    } else {
      await addCustomer(form.value).finally(() => buttonLoading.value = false);
    }
    proxy?.$modal.msgSuccess("操作成功");
    dialog.visible = false;
    await getList();

  });
}

/** 删除按钮操作 */
const handleDelete = async (row?: CustomerVO) => {
  const _ids = row?.id || ids.value;
  await proxy?.$modal.confirm('是否确认删除下游客户编号为"' + _ids + '"的数据项？').finally(() => loading.value = false);
  await delCustomer(_ids);
  proxy?.$modal.msgSuccess("删除成功");
  await getList();
}

/** 导出按钮操作 */
const handleExport = () => {
  proxy?.download('system/customer/export', {
    ...queryParams.value
  }, `customer_${new Date().getTime()}.xlsx`)
}

const allCorporateList = ref<CorporateVO[]>([]);
const getCorporateList = async () => {
  const res = await listCorporateAll();
  console.log("getCorporateList", res);
  allCorporateList.value = res.data;
  console.log("allCorporateList", allCorporateList.value);
}


// 添加methodParams定义
const methodParams = reactive({
  cmpp: {
    spCode: '',//接入码
    connections: '',//连接数
    acceptRate: '',//受理速率
    needProviderDest: 1//回执带入上游码号 0 不带入 1 带入
  },
  http: {
    acceptRate: ''//受理速率
  }
});
const needProviderDestList = ref<any[]>([
  {value: 0, label: '不带入'},
  {value: 1, label: '带入'}
])

// 添加方法处理接入方式变更
const handleMethodChange = (method: string) => {
  // 可以在这里重置参数或做其他处理
};
const  allProviderChannels = ref<ProviderChannelVO[]>([]);
const getAllProviderChannel = async () => {
  const res = await listAllProviderChannel();
  allProviderChannels.value = res;
  console.log("allProviderChannels", allProviderChannels.value);
}

// 添加数据
const channelDialog = reactive({
  visible: false,
  customerId: null as string | number | null
});
const channelList = ref<CustomerProviderChannelVO[]>([]);

// 打开通道配置对话框
const openChannelDialog = (customerId: string | number) => {
  channelDialog.visible = true;
  channelDialog.customerId = customerId;
  // 这里应该加载该客户已有的通道配置
  loadCustomerChannels(customerId);
};
// 加载客户通道配置
const loadCustomerChannels = async (customerId: string | number) => {
  // 调用API获取该客户的通道配置
  const res = await getCustomerChannels(customerId);
  console.log("loadCustomerChannels", res.data);
  channelList.value = res.data || [];
};
// 添加通道
const addChannel = () => {
  channelList.value.push({
    providerChannelId: undefined,
    customerId: channelDialog.customerId,
    weight: 50,
    status: 1
  });
};

// 删除通道
const removeChannel = (index: number) => {
  channelList.value.splice(index, 1);
};
// 保存通道配置
const saveChannels = async () => {
  try {
    const res = await bindProviderChannel(channelDialog.customerId, channelList.value);
    console.log("bindProviderChannel",res);
    proxy?.$modal.msgSuccess("保存成功");
    channelDialog.visible = false;
  } catch (e) {
    proxy?.$modal.msgError("保存失败");
  }
};
onMounted(() => {
  getList();
  getCorporateList();
  getAllProviderChannel();
});
</script>
